package com.abhinav.spring.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractHibernateDAO<T extends Serializable> {

	private Class<T> type;

	@Autowired
	SessionFactory sessionFactory;

	public void setType(final Class<T> typeToSet) {
		this.type = typeToSet;
	}

	public T findOne(final Long id) {
		return (T) getCurrentSession().get(type, id);
	}
	
	public List<T> findAll(){
		return getCurrentSession().createQuery("from " + type.getName()).list();
	}
	
	public void save(final T entity){
		getCurrentSession().save(entity);
	}
	
	public void update(final T entity){
		getCurrentSession().merge(entity);
	}
	
	public void delete(final T entity){
		getCurrentSession().delete(entity);
	}
	
	public void deleteById(final Long entityId){
		final T entity = findOne(entityId);
		delete(entity);
	}

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}
